#include <ArduinoJson.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <FS.h>

// 建立ESP8266WiFiMulti对象
ESP8266WiFiMulti wifiMulti;

void setup()
{
    Serial.begin(9600);
    Serial.println("");

    // 启动闪存文件系统
    if (SPIFFS.begin())
    {
        Serial.println("SPIFFS Started.");
    }
    else
    {
        Serial.println("SPIFFS Failed to Start.");
    }

    // 建立DynamicJsonDocument对象
    const size_t capacity = JSON_OBJECT_SIZE(1) + JSON_OBJECT_SIZE(2) + 60;
    DynamicJsonDocument doc(capacity);

    // 从闪存文件系统中读取即将解析的json文件
    File file = SPIFFS.open("/config.json", "r");

    // 反序列化数据
    deserializeJson(doc, file);

    // 获取解析后的数据信息
    const char *wifi_ssid = doc["wifi"]["ssid"];         // "taichimaker"
    const char *wifi_password = doc["wifi"]["password"]; // "12345678"

    // 尝试联网
    wifiMulti.addAP(wifi_ssid, wifi_password);
    wifiMulti.addAP("ssid_from_AP_2", "your_password_for_AP_2");
    wifiMulti.addAP("ssid_from_AP_3", "your_password_for_AP_3");
    Serial.println("Connecting ...");

    int i = 0;
    while (wifiMulti.run() != WL_CONNECTED)
    { // 尝试进行wifi连接。
        delay(1000);
        Serial.print(i++);
        Serial.print(' ');
    }

    Serial.println("");
    Serial.print("Connected to ");
    Serial.println(WiFi.SSID()); // WiFi名称
    Serial.print("IP address:\t");
    Serial.println(WiFi.localIP()); // IP
}

void loop() {}